package com.lovi.homework;

import java.util.Objects;
import java.util.TreeSet;

@SuppressWarnings({"all"})
public class Homework06 {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet();
        //分析源码
        //add 方法，因为 TreeSet() 构造器没有传入Comparator接口的匿名内部类
        //所以在底层 Comparable<? super K> k = (Comparable<? super K>) key;
        //即 把 Perosn转成 Comparable类型
        treeSet.add(new Person("l"));//ClassCastException.
        treeSet.add(new Person("lovi"));//ClassCastException.
        treeSet.add(new Person("lo"));//ClassCastException.
        treeSet.add(new Person("lovi1"));//ClassCastException.
        treeSet.add(new Person("lov"));//ClassCastException.


        System.out.println(treeSet);


    }
}

class Person implements Comparable{
    private String name;
    private int age;

    public Person(String name) {
        this.name = name;
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Object o) {
        Person p = (Person)o;
        //根据名称的长度从长到短[新的-旧的，所以是从长到短]
        return p.getName().length() - this.getName().length();
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "\nPerson{" +
                "name='" + name + '\'' +
                '}';
    }
}

